package com.fancy.gateway.filter;

import com.fancy.common.dto.response.Result;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * 全局异常处理过滤器
 *
 * @author fancy
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class GlobalExceptionFilter implements GlobalFilter, Ordered {

    private final ObjectMapper objectMapper;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        return chain.filter(exchange)
                .onErrorResume(throwable -> {
                    log.error("网关处理请求时发生异常: {}", throwable.getMessage(), throwable);
                    return handleException(exchange, throwable);
                });
    }

    /**
     * 处理异常
     */
    private Mono<Void> handleException(ServerWebExchange exchange, Throwable throwable) {
        ServerHttpResponse response = exchange.getResponse();

        int code;
        String message;
        HttpStatus status;

        if (throwable instanceof org.springframework.cloud.gateway.support.TimeoutException) {
            // 超时异常
            code = 50001;
            message = "服务请求超时";
            status = HttpStatus.GATEWAY_TIMEOUT;
        } else if (throwable instanceof org.springframework.web.server.ResponseStatusException) {
            // 响应状态异常
            org.springframework.web.server.ResponseStatusException ex =
                (org.springframework.web.server.ResponseStatusException) throwable;
            status = ex.getStatus();
            code = status.value();
            message = ex.getReason() != null ? ex.getReason() : "服务异常";
        } else if (throwable.getCause() instanceof java.net.ConnectException) {
            // 连接异常
            code = 50002;
            message = "服务连接失败";
            status = HttpStatus.SERVICE_UNAVAILABLE;
        } else {
            // 其他异常
            code = 50000;
            message = "系统异常";
            status = HttpStatus.INTERNAL_SERVER_ERROR;
        }

        return buildErrorResponse(response, status, code, message);
    }

    /**
     * 构建错误响应
     */
    private Mono<Void> buildErrorResponse(ServerHttpResponse response, HttpStatus status, int code, String message) {
        response.setStatusCode(status);
        response.getHeaders().add("Content-Type", MediaType.APPLICATION_JSON_VALUE);

        Result<Object> result = Result.fail(code, message);

        try {
            String body = objectMapper.writeValueAsString(result);
            DataBuffer buffer = response.bufferFactory().wrap(body.getBytes(StandardCharsets.UTF_8));
            return response.writeWith(Mono.just(buffer));
        } catch (JsonProcessingException e) {
            log.error("构建异常响应失败", e);
            return response.setComplete();
        }
    }

    @Override
    public int getOrder() {
        return -1;
    }
}
